<template>
  <div class="register-container">
    <!-- 注册内容 -->
    <div class="register">
      <h3>
        注册新用户
        <span class="go"
          >我有账号，去
          <a href="login.html" target="_blank">登录</a>
        </span>
      </h3>
      <!-- 
        通过作用域插槽，
          ValidationObserver（子组件）向当前组件（Register 父组件）传递数据： handleSubmit
          handleSubmit方法作用：能校验整个表单
      -->
      <ValidationObserver v-slot="{ handleSubmit }" ref="formRef">
        <!-- 
          当提交表单时，触发submit事件，执行handleSubmit函数，校验整个表单，
          校验通过就会调用register函数
          校验失败，会相应做出错误提示，register函数不会触发
         -->
        <form @submit.prevent="handleSubmit(register)">
          <!-- 将所有表单项放入form内 -->
          <!-- 
            ValidationProvider 默认渲染span元素，样式出现问题。希望得到div
              class="content" 类名
              name="phone" 表单项名称
              rules 表单校验规则（需要先定义才能使用）
              v-slot="{ errors }" 作用域插槽，可以得到表单校验失败的错误信息
              tag="div" 会渲染div元素
              mode="lazy" 失去焦点触发表单校验
           -->
          <ValidationProvider
            class="content"
            name="phone"
            rules="phoneRequired|phone"
            v-slot="{ errors }"
            tag="div"
            mode="lazy"
          >
            <label>手机号:</label>
            <input
              type="text"
              placeholder="请输入你的手机号"
              v-model="user.phone"
            />
            <span class="error-msg">{{ errors[0] }}</span>
          </ValidationProvider>
          <ValidationProvider
            class="content"
            name="code"
            rules="codeRequired|code"
            v-slot="{ errors }"
            tag="div"
            mode="lazy"
          >
            <label>验证码:</label>
            <input type="text" placeholder="请输入验证码" v-model="user.code" />
            <button
              class="getcode"
              @click.prevent="getCode"
              :disabled="time <= 60"
            >
              {{
                time <= 60
                  ? time + "秒后重新发送"
                  : isSendCode
                  ? "重新获取"
                  : "获取验证码"
              }}
            </button>
            <span class="error-msg">{{ errors[0] }}</span>
          </ValidationProvider>
          <ValidationProvider
            class="content"
            name="password"
            rules="passwordRequired|password"
            v-slot="{ errors }"
            tag="div"
            mode="lazy"
          >
            <label>登录密码:</label>
            <input
              type="text"
              placeholder="请输入你的登录密码"
              v-model="user.password"
            />
            <span class="error-msg">{{ errors[0] }}</span>
          </ValidationProvider>
          <ValidationProvider
            class="content"
            name="rePassword"
            :rules="`rePasswordRequired|rePassword:${user.password}`"
            v-slot="{ errors }"
            tag="div"
            mode="lazy"
          >
            <label>确认密码:</label>
            <input
              type="text"
              placeholder="请输入确认密码"
              v-model="user.rePassword"
            />
            <span class="error-msg">{{ errors[0] }}</span>
          </ValidationProvider>
          <ValidationProvider
            name="isAgree"
            rules="isAgree"
            v-slot="{ errors }"
            tag="div"
            mode="lazy"
            class="controls"
          >
            <input name="m1" type="checkbox" v-model="user.isAgree" />
            <span>同意协议并注册《尚品汇用户协议》</span>
            <span class="error-msg">{{ errors[0] }}</span>
          </ValidationProvider>
          <div class="btn">
            <button>完成注册</button>
          </div>
        </form>
      </ValidationObserver>
    </div>

    <!-- 底部 -->
    <div class="copyright">
      <ul>
        <li>关于我们</li>
        <li>联系我们</li>
        <li>联系客服</li>
        <li>商家入驻</li>
        <li>营销中心</li>
        <li>手机尚品汇</li>
        <li>销售联盟</li>
        <li>尚品汇社区</li>
      </ul>
      <div class="address">地址：北京市昌平区宏福科技园综合楼6层</div>
      <div class="beian">京ICP备19006430号</div>
    </div>
  </div>
</template>

<script>
import { ValidationObserver, ValidationProvider, extend } from "vee-validate";
import { required } from "vee-validate/dist/rules";
import { reqSendCode, reqRegister } from "@/api/user";
import { phoneReg } from "@/utils/rules";

// https://vee-validate.logaretm.com/v3/guide/forms.html#validate-before-submit
// https://vee-validate.logaretm.com/v3/guide/rules.html#importing-the-rules

const codeReg = /^[0-9]{6}$/;

extend("codeRequired", {
  ...required,
  message: "验证码必填",
});

extend("code", {
  validate(val) {
    return codeReg.test(val);
  },
  message: "请填写正确的验证码",
});

extend("rePasswordRequired", {
  ...required,
  message: "确认密码必填",
});

extend("rePassword", {
  validate(val, { password }) {
    return val === password;
  },
  message: "两次密码必须输入一致",
  params: ["password"], // 声明接受参数
});

extend("isAgree", {
  validate(val) {
    return val;
  },
  message: "请阅读并同意尚品汇用户协议",
});

export default {
  name: "XRegister",
  components: {
    ValidationObserver,
    ValidationProvider,
  },
  data() {
    return {
      user: {
        phone: "",
        code: "",
        password: "",
        rePassword: "",
        isAgree: false,
      },
      time: 61,
      isSendCode: false,
    };
  },
  methods: {
    async register() {
      // 表单校验通过，触发的函数
      const { phone, password, code } = this.user;
      await reqRegister({ phone, password, code });
      this.$router.push("/login");
    },
    // 获取验证码
    async getCode() {
      const phone = this.user.phone;
      if (!phoneReg.test(phone)) {
        // 设置表单的错误
        this.$refs.formRef.setErrors({
          phone: ["请输入手机号，在发送验证码"],
        });
        return;
      }
      sessionStorage.setItem("isSendCode", true);
      this.isSendCode = true;
      this.setInterval();
      // 1. 发送请求，获取验证码
      const code = await reqSendCode(phone);
      console.log(code);
    },
    setInterval() {
      // 2. 倒计时效果
      this.time--;
      this.timeId = setTimeout(() => {
        if (this.time <= 1) {
          this.time = 61;
          sessionStorage.setItem("isSendCode", false);
          return;
        }
        this.setInterval();
      }, 1000);
    },
  },
  mounted() {
    const isSendCode = JSON.parse(sessionStorage.getItem("isSendCode"));
    /*
      读取isSendCode是字符串类型 'true' 'false'
        字符串只要有值，转布尔值就是true
        所以：'false'也会变成true
    */
    if (isSendCode) {
      this.isSendCode = true;
      this.setInterval();
    }
  },
  beforeDestroy() {
    clearTimeout(this.timeId);
  },
};
</script>

<style lang="less" scoped>
.register-container {
  .register {
    width: 1200px;
    height: 445px;
    border: 1px solid rgb(223, 223, 223);
    margin: 0 auto;

    h3 {
      background: #ececec;
      margin: 0;
      padding: 6px 15px;
      color: #333;
      border-bottom: 1px solid #dfdfdf;
      font-size: 20.04px;
      line-height: 30.06px;

      span {
        font-size: 14px;
        float: right;

        a {
          color: #e1251b;
        }
      }
    }

    div:nth-of-type(1) {
      margin-top: 40px;
    }

    .content {
      padding-left: 390px;
      margin-bottom: 18px;
      position: relative;

      label {
        font-size: 14px;
        width: 96px;
        text-align: right;
        display: inline-block;
      }

      input {
        width: 270px;
        height: 38px;
        padding-left: 8px;
        box-sizing: border-box;
        margin-left: 5px;
        outline: none;
        border: 1px solid #999;
      }

      img {
        vertical-align: sub;
      }

      .error-msg {
        position: absolute;
        top: 100%;
        left: 495px;
        color: red;
      }
    }

    .controls {
      text-align: center;
      position: relative;

      input {
        vertical-align: middle;
      }

      .error-msg {
        position: absolute;
        top: 100%;
        left: 495px;
        color: red;
      }
    }

    .btn {
      text-align: center;
      line-height: 36px;
      margin: 17px 0 0 55px;

      button {
        outline: none;
        width: 270px;
        height: 36px;
        background: #e1251b;
        color: #fff !important;
        display: inline-block;
        font-size: 16px;
      }
    }

    .getcode {
      height: 38px;
      margin-left: 10px;
      padding: 5px;
      &:disabled {
        color: #ddd;
      }
    }
  }

  .copyright {
    width: 1200px;
    margin: 0 auto;
    text-align: center;
    line-height: 24px;

    ul {
      li {
        display: inline-block;
        border-right: 1px solid #e4e4e4;
        padding: 0 20px;
        margin: 15px 0;
      }
    }
  }
}
</style>
